home *** CD-ROM | disk | FTP | other *** search
/ The CICA Windows Explosion! / The CICA Windows Explosion! - Disc 2.iso / demo / wemdemo4.zip / INFO / ELISP.5 < prev    next >
Text File  |  1994-09-21  |  52KB  |  1,311 lines

  1. Info file elisp, produced by Makeinfo, -*- Text -*- from input file
  2. elisp.texi.
  3.  
  4.    This file documents GNU Emacs Lisp.
  5.  
  6.    This is edition 1.03 of the GNU Emacs Lisp Reference Manual,   for
  7. Emacs Version 18.
  8.  
  9.    Published by the Free Software Foundation, 675 Massachusetts
  10. Avenue,  Cambridge, MA 02139 USA
  11.  
  12.    Copyright (C) 1990 Free Software Foundation, Inc.
  13.  
  14.    Permission is granted to make and distribute verbatim copies of
  15. this manual provided the copyright notice and this permission notice
  16. are preserved on all copies.
  17.  
  18.    Permission is granted to copy and distribute modified versions of
  19. this manual under the conditions for verbatim copying, provided that
  20. the entire resulting derived work is distributed under the terms of a
  21. permission notice identical to this one.
  22.  
  23.    Permission is granted to copy and distribute translations of this
  24. manual into another language, under the above conditions for modified
  25. versions, except that this permission notice may be stated in a
  26. translation approved by the Foundation.
  27.  
  28.  
  29. 
  30. File: elisp,  Node: Vectors,  Prev: Array Functions,  Up: Sequences Arrays Vectors
  31.  
  32. Vectors
  33. =======
  34.  
  35.    Arrays in Lisp, like arrays in most languages, are blocks of
  36. memory whose elements can be accessed in constant time.  A "vector"
  37. is a general-purpose array; its elements can be any Lisp objects. 
  38. (The other kind of array provided in Emacs Lisp is the "string",
  39. whose elements must be characters.)  The main uses of vectors in
  40. Emacs are as syntax tables (vectors of integers) and keymaps (vectors
  41. of commands).  They are also used internally as part of the
  42. representation of a byte-compiled function; if you print such a
  43. function, you will see a vector in it.
  44.  
  45.    The indices of the elements of a vector are numbered starting with
  46. zero in Emacs Lisp.
  47.  
  48.    Vectors are printed with square brackets surrounding the elements
  49. in their order.  Thus, a vector containing the symbols `a', `b' and
  50. `c' is printed as `[a b c]'.  You can write vectors in the same way
  51. in Lisp input.
  52.  
  53.    A vector, like a string or a number, is considered a constant for
  54. evaluation: the result of evaluating it is the same vector.  The
  55. elements of the vector are not evaluated.  *Note Self-Evaluating
  56. Forms::.
  57.  
  58.    Here are examples of these principles:
  59.  
  60.      (setq avector [1 two '(three) "four" [five]])
  61.           => [1 two (quote (three)) "four" [five]]
  62.      (eval avector)
  63.           => [1 two (quote (three)) "four" [five]]
  64.      (eq avector (eval avector))
  65.           => t
  66.  
  67.    Here are some functions that relate to vectors:
  68.  
  69.  * Function: vectorp OBJECT
  70.      This function returns `t' if OBJECT is a vector.
  71.  
  72.           (vectorp [a])
  73.                => t
  74.           (vectorp "asdf")
  75.                => nil
  76.  
  77.  * Function: vector &rest OBJECTS
  78.      This function creates and returns a vector whose elements are
  79.      the arguments, OBJECTS.
  80.  
  81.           (vector 'foo 23 [bar baz] "rats")
  82.                => [foo 23 [bar baz] "rats"]
  83.           (vector)
  84.                => []
  85.  
  86.  * Function: make-vector INTEGER OBJECT
  87.      This function returns a new vector consisting of INTEGER
  88.      elements, each initialized to OBJECT.
  89.  
  90.           (setq sleepy (make-vector 9 'Z))
  91.                => [Z Z Z Z Z Z Z Z Z]
  92.  
  93.  * Function: vconcat &rest SEQUENCES
  94.      This function returns a new vector containing all the elements
  95.      of the SEQUENCES.  The arguments SEQUENCES may be lists,
  96.      vectors, or strings.  If no SEQUENCES are given, an empty vector
  97.      is returned.
  98.  
  99.      The value is a newly constructed vector that is not `eq' to any
  100.      existing vector.
  101.  
  102.           (setq a (vconcat '(A B C) '(D E F)))
  103.                => [A B C D E F]
  104.           (eq a (vconcat a))
  105.                => nil
  106.           (vconcat)
  107.                => []
  108.           (vconcat [A B C] "aa" '(foo (6 7)))
  109.                => [A B C 97 97 foo (6 7)]
  110.  
  111.      When an argument is an integer (not a sequence of integers), it
  112.      is converted to a string of digits making up the decimal printed
  113.      representation of the integer.  This special case exists for
  114.      compatibility with Mocklisp, and we don't recommend you take
  115.      advantage of it.  If you want to convert an integer in this way,
  116.      use `format' (*note Formatting Strings::.) or `int-to-string'
  117.      (*note String Conversion::.).
  118.  
  119.      For other concatenation functions, see `mapconcat' in *Note
  120.      Mapping Functions::, `concat' in *Note Creating Strings::, and
  121.      `append' in *Note Building Lists::.
  122.  
  123.    The `append' function may be used to convert a vector into a list
  124. with the same elements (*note Building Lists::.):
  125.  
  126.      (setq avector [1 two (quote (three)) "four" [five]])
  127.           => [1 two (quote (three)) "four" [five]]
  128.      (append avector nil)
  129.           => (1 two (quote (three)) "four" [five])
  130.  
  131.  
  132. 
  133. File: elisp,  Node: Symbols,  Next: Evaluation,  Prev: Sequences Arrays Vectors,  Up: Top
  134.  
  135. Symbols
  136. *******
  137.  
  138.    A "symbol" is an object with a unique name.  This chapter
  139. describes symbols, their components, and how they are created and
  140. interned.  Property lists are also described.  The uses of symbols as
  141. variables and as function names are described in separate chapters;
  142. see *Note Variables::, and *Note Functions::.
  143.  
  144.    You may test whether an arbitrary Lisp object is a symbol with
  145. `symbolp':
  146.  
  147.  * Function: symbolp OBJECT
  148.      This function returns `t' if OBJECT is a symbol, `nil' otherwise.
  149.  
  150. * Menu:
  151.  
  152. * Symbol Components::        Symbols have names, values, function definitions
  153.                                and property lists.
  154. * Definitions::              A definition says how a symbol will be used.
  155. * Creating Symbols::         How symbols are kept unique.
  156. * Property Lists::           Each symbol has a property list
  157.                                for recording miscellaneous information.
  158.  
  159.  
  160. 
  161. File: elisp,  Node: Symbol Components,  Next: Definitions,  Prev: Symbols,  Up: Symbols
  162.  
  163. Symbol Components
  164. =================
  165.  
  166.    Each symbol has four components (or "cells"), each of which
  167. references another object:
  168.  
  169. Print name
  170.      The "print name cell" holds a string which names the symbol for
  171.      reading and printing.  See `symbol-name' in *Note Creating
  172.      Symbols::.
  173.  
  174. Value
  175.      The "value cell" holds the current value of the symbol as a
  176.      variable.  When a symbol is used as a form, the value of the
  177.      form is the contents of the symbol's value cell.  See
  178.      `symbol-value' in *Note Accessing Variables::.
  179.  
  180. Function
  181.      The "function cell" holds the function definition of the symbol.
  182.      When a symbol is used as a function, its function definition is
  183.      used in its place.  This cell is also used by the editor command
  184.      loop to record keymaps and keyboard macros.  Because each symbol
  185.      has separate value and function cells, variables and function
  186.      names do not conflict.  See `symbol-function' in *Note Function
  187.      Cells::.
  188.  
  189. Property list
  190.      The "property list cell" holds the property list of the symbol. 
  191.      See `symbol-plist' in *Note Property Lists::.
  192.  
  193.    The print name cell always holds a string, and cannot be changed. 
  194. The other three cells can be set individually to any specified Lisp
  195. object.
  196.  
  197.    The print name cell holds the string that is the name of the symbol.
  198. Since symbols are represented textually by their names, it is
  199. important not to have two symbols with the same name.  The Lisp
  200. reader ensures this: every time it reads a symbol, it looks for an
  201. existing symbol with the specified name before it creates a new one. 
  202. (In GNU Emacs Lisp, this is done with a hashing algorithm that uses
  203. an obarray; see *Note Creating Symbols::.)
  204.  
  205.    In normal usage, the function cell usually contains a function or
  206. macro, as that is what the Lisp interpreter expects to see there
  207. (*note Evaluation::.).  Keyboard macros (*note Keyboard Macros::.),
  208. keymaps (*note Keymaps::.) and autoload objects (*note
  209. Autoloading::.) are also sometimes stored in the function cell of
  210. symbols.  We often refer to "the function `foo'" when we really mean
  211. the function stored in the function cell of the symbol `foo'.  The
  212. distinction will be made only when necessary.
  213.  
  214.    Similarly, the property list cell normally holds a correctly
  215. formatted property list (*note Property Lists::.), as a number of
  216. functions will expect to see a property list there.
  217.  
  218.    The function cell or the value cell may be "void", which means
  219. that the cell does not reference any object.  (This is not the same
  220. thing as holding the symbol `void', nor the same as holding the
  221. symbol `nil'.)  Examining the value of a cell which is void results
  222. in an error, such as `Symbol's value as variable is void'.
  223.  
  224.    The four functions `symbol-name', `symbol-value', `symbol-plist',
  225. and `symbol-function' return the contents of the four cells.  Here as
  226. an example we show the contents of the four cells of the symbol
  227. `buffer-file-name':
  228.  
  229.      (symbol-name 'buffer-file-name)
  230.           => "buffer-file-name"
  231.      (symbol-value 'buffer-file-name)
  232.           => "/gnu/elisp/symbols.texi"
  233.      (symbol-plist 'buffer-file-name)
  234.           => (variable-documentation 29529)
  235.      (symbol-function 'buffer-file-name)
  236.           => #<subr buffer-file-name>
  237.  
  238. Because this symbol is the variable which holds the name of the file
  239. being visited in the current buffer, the value cell contents we see
  240. are the name of the source file of this chapter of the Emacs Lisp
  241. Manual.  The property list cell contains the list
  242. `(variable-documentation 29529)' which tells the documentation
  243. functions where to find documentation about `buffer-file-name' in the
  244. `DOC' file.  (29529 is the offset from the beginning of the `DOC'
  245. file where the documentation for the function begins.)  The function
  246. cell contains the function for returning the name of the file.  Since
  247. `buffer-file-name' is a primitive function, its function definition
  248. has no read syntax and prints in hash notation (*note Primitive
  249. Function Type::.).  A function definition written in Lisp will have a
  250. lambda expression (or byte-code) in this cell.
  251.  
  252.  
  253. 
  254. File: elisp,  Node: Definitions,  Next: Creating Symbols,  Prev: Symbol Components,  Up: Symbols
  255.  
  256. Defining Symbols
  257. ================
  258.  
  259.    A "definition" in Lisp is a special form that announces your
  260. intention to use a certain symbol in a particular way.  In Emacs
  261. Lisp, you can define a symbol as a variable, or define it as a
  262. function (or macro), or both independently.
  263.  
  264.    A definition construct typically specifies a value or meaning for
  265. the symbol for one kind of use, plus documentation for its meaning
  266. when used in this way.  Thus, when you define a symbol as a variable,
  267. you can supply an initial value for the variable, plus documentation
  268. for the variable.
  269.  
  270.    `defvar' and `defconst' are definitions that establish a symbol as
  271. a global variable.  They are documented in detail in *Note Defining
  272. Variables::.
  273.  
  274.    `defun' defines a symbol as a function, creating a lambda
  275. expression and storing it in the function cell of the symbol.  This
  276. lambda expression thus becomes the function definition of the symbol.
  277. (The term "function definition", meaning the contents of the function
  278. cell, is derived from the idea that `defun' gives the symbol its
  279. definition as a function.)  *Note Functions::.
  280.  
  281.    `defmacro' defines a symbol as a macro.  It creates a macro object
  282. and stores it in the function cell of the symbol.  Note that a given
  283. symbol can be a macro or a function, but not both at once, because
  284. both macro and function definitions are kept in the function cell,
  285. and that cell can hold only one Lisp object at any given time.  *Note
  286. Macros::.
  287.  
  288.    In GNU Emacs Lisp, a definition is not required in order to use a
  289. symbol as a variable or function.  Thus, you can make a symbol a
  290. global variable with `setq', whether you define it first or not.  The
  291. real purpose of definitions is to guide programmers and programming
  292. tools.  They inform programmers who read the code that certain
  293. symbols are *intended* to be used as variables, or as functions.  In
  294. addition, utilities such as `etags' and `make-docfile' can recognize
  295. definitions, and add the appropriate information to tag tables and
  296. the `emacs/etc/DOC-VERSION' file. *Note Accessing Documentation::.
  297.  
  298.  
  299. 
  300. File: elisp,  Node: Creating Symbols,  Next: Property Lists,  Prev: Definitions,  Up: Symbols
  301.  
  302. Creating and Interning Symbols
  303. ==============================
  304.  
  305.    To understand how symbols are created in GNU Emacs Lisp, it is
  306. necessary to know how Lisp reads them.  It is essential to ensure
  307. that every time Lisp reads the same set of characters, it finds the
  308. same symbol.  Failure to do so would be disastrous.
  309.  
  310.    When the Lisp reader encounters a symbol, it reads all the
  311. characters of the name.  Then it "hashes" those characters to find an
  312. index in a table called an "obarray".  Hashing is an efficient method
  313. of looking something up.  For example, instead of searching a
  314. telephone book cover to cover when looking up Jan Jones, you start
  315. with the J's and go from there.  That is a simple version of hashing.
  316. Each element of the obarray is a "bucket" which holds all the symbols
  317. with a given hash code; to look for a given name, it is sufficient to
  318. look through all the symbols in the bucket for that name's hash code.
  319.  
  320.    If a symbol with the desired name is found, then it is used.  If
  321. no such symbol is found, then a new symbol is created and added to
  322. the obarray bucket.  Adding a symbol to an obarray is called
  323. "interning" it, and the symbol is then called an "interned symbol". 
  324. In Emacs Lisp, a symbol may be interned in only one obarray.
  325.  
  326.      Common Lisp note: in Common Lisp, a symbol may be interned in
  327.      several obarrays at once.
  328.  
  329.    If a symbol is not in the obarray, then there is no way for Lisp
  330. to find it when its name is read.  Such a symbol is called an
  331. "uninterned symbol" relative to the obarray.  An uninterned symbol
  332. has all the other characteristics of symbols.  It is possible, though
  333. uncommon, for two different symbols to have the same name in
  334. different obarrays; they are not `eq' or `equal'.
  335.  
  336.    In Emacs Lisp, an obarray is represented as a vector.  Each
  337. element of the vector is a bucket; its value is either an interned
  338. symbol whose name hashes to that bucket, or 0 if the bucket is empty.
  339. Each interned symbol has an internal link (invisible to the user) to
  340. the next symbol in the bucket.  Because these links are invisible,
  341. there is no way to scan the symbols in an obarray except using
  342. `mapatoms' (below).  The order of symbols in a bucket is not
  343. significant.
  344.  
  345.    In an empty obarray, every element is 0, and you can create an
  346. obarray with `(make-vector LENGTH 0)'.  Prime numbers as lengths tend
  347. to result in good hashing; lengths one less than a power of two are
  348. also good.
  349.  
  350.    Most of the functions below take a name and sometimes an obarray
  351. as arguments.  A `wrong-type-argument' error is signaled if the name
  352. is not a string, or if the obarray is not a vector.
  353.  
  354.  * Function: symbol-name SYMBOL
  355.      This function returns the string that is SYMBOL's name.  For
  356.      example:
  357.  
  358.              (symbol-name 'foo)
  359.                => "foo"
  360.  
  361.      Changing the string by substituting characters, etc, will change
  362.      the name of the symbol, but will fail to update the obarray, so
  363.      don't do it!
  364.  
  365.  * Function: make-symbol NAME
  366.      This function returns a newly-allocated uninterned symbol whose
  367.      name is NAME (which must be a string).  Its value and function
  368.      definition are void, and its property list is `nil'.  In the
  369.      example below, the value of `sym' is not `eq' to `foo' because
  370.      it is a distinct uninterned symbol whose name is also `foo'.
  371.  
  372.           (setq sym (make-symbol "foo"))
  373.                => foo
  374.           (eq sym 'foo)
  375.                => nil
  376.  
  377.  * Function: intern NAME &optional OBARRAY
  378.      This function returns the interned symbol whose name is NAME. 
  379.      If there is no such symbol in the obarray, a new one is created,
  380.      added to the obarray, and returned.  If OBARRAY is supplied, it
  381.      specifies the obarray to use; otherwise, the value of the global
  382.      variable `obarray' is used.
  383.  
  384.           (setq sym (intern "foo"))
  385.                => foo
  386.           (eq sym 'foo)
  387.                => t
  388.  
  389.  * Function: intern-soft NAME &optional OBARRAY
  390.      This function returns the symbol whose name is NAME, or `nil' if
  391.      a symbol with that name is not found in the obarray.  Therefore,
  392.      you can use `intern-soft' to test whether a symbol with a given
  393.      name is interned.  If OBARRAY is supplied, it specifies the
  394.      obarray to use; otherwise the value of the global variable
  395.      `obarray' is used.
  396.  
  397.           (intern-soft "frazzle")                ; No such symbol exists.
  398.                => nil
  399.           (make-symbol "frazzle")                ; Create an uninterned one.
  400.                => frazzle
  401.           (intern-soft "frazzle")                ; That one cannot be found.
  402.                => nil
  403.           (setq sym (intern "frazzle"))          ; Create an interned one.
  404.                => frazzle
  405.           (intern-soft "frazzle")                ; That one can be found!
  406.                => frazzle
  407.  
  408.              (eq sym 'frazzle)                      ; And it is the same one.
  409.                => t
  410.  
  411.  * Variable: obarray
  412.      This variable is the standard obarray for use by `intern' and
  413.      `read'.
  414.  
  415.  * Function: mapatoms FUNCTION &optional OBARRAY
  416.      This function applies FUNCTION to every symbol in OBARRAY.  It
  417.      returns `nil'.  If OBARRAY is not supplied, it defaults to the
  418.      value of `obarray', the standard obarray for ordinary symbols.
  419.  
  420.           (setq count 0)
  421.                => 0
  422.           (defun count-syms (s)
  423.             (setq count (1+ count)))
  424.                => count-syms
  425.           (mapatoms 'count-syms)
  426.                => nil
  427.           count
  428.                => 1871
  429.  
  430.      See `documentation' in *Note Accessing Documentation::, for
  431.      another example using `mapatoms'.
  432.  
  433.  
  434. 
  435. File: elisp,  Node: Property Lists,  Prev: Creating Symbols,  Up: Symbols
  436.  
  437. Property Lists
  438. ==============
  439.  
  440.    A "property list" ("plist" for short) is a list of paired elements
  441. stored in the property list cell of a symbol.  Each of the pairs
  442. associates a property name (usually a symbol) with a property or
  443. value.  Property lists are generally used to record information about
  444. a symbol, such as how to compile it, the name of the file where it
  445. was defined, or perhaps even the grammatical class of the symbol
  446. (representing a word) in a language understanding system.
  447.  
  448.    The property names and property values may be any Lisp objects,
  449. but the names are usually symbols.  They are compared using `eq'. 
  450. Here is an example of a property list, found on the symbol `progn'
  451. when the compiler is loaded:
  452.  
  453.      (lisp-indent-hook 0 byte-compile byte-compile-progn)
  454.  
  455. Here `lisp-indent-hook' and `byte-compile' are property names, and
  456. the other two elements are the corresponding values.
  457.  
  458.    Association lists (*note Association Lists::.) are very similar to
  459. property lists.  In contrast to association lists, the order of the
  460. pairs in the property list is not significant since the property
  461. names must be distinct.
  462.  
  463.    Property lists are better than association lists when it is
  464. necessary to attach information to various Lisp function names or
  465. variables.  If all the pairs are recorded in one association list, it
  466. will be necessary to search that entire list each time a function or
  467. variable is to be operated on.  By contrast, if the information is
  468. recorded in the property lists of the function names or variables
  469. themselves, each search will scan only the length of one property
  470. list, which is usually short.  For this reason, the documentation for
  471. a variable is recorded in a property named `variable-documentation'. 
  472. The byte compiler likewise uses properties to record those functions
  473. needing special treatment.
  474.  
  475.    However, association lists have their own advantages.  Depending
  476. on your application, it may be faster to add an association to the
  477. front of an association list than to update a property.  All
  478. properties for a symbol are stored in the same property list, so
  479. there is a possibility of a conflict between different uses of a
  480. property name.  (For this reason, it is a good idea to use property
  481. names that are probably unique, such as by including the name of the
  482. library in the property name.)  An association list may be used like
  483. a stack where associations are pushed on the front of the list and
  484. later discarded; this is not possible with a property list.
  485.  
  486.  * Function: symbol-plist SYMBOL
  487.      This function returns the property list of SYMBOL.
  488.  
  489.  * Function: setplist SYMBOL PLIST
  490.      This function sets SYMBOL's property list to PLIST.  Normally,
  491.      PLIST should be a well-formed property list, but this is not
  492.      enforced.
  493.  
  494.           (setplist 'foo '(a 1 b (2 3) c nil))
  495.                => (a 1 b (2 3) c nil)
  496.           (symbol-plist 'foo)
  497.                => (a 1 b (2 3) c nil)
  498.  
  499.      For symbols in special obarrays, which are not used for ordinary
  500.      purposes, it may make sense to use the property list cell in a
  501.      nonstandard fashion; in fact, the abbrev mechanism does so
  502.      (*note Abbrevs::.).
  503.  
  504.  * Function: get SYMBOL PROPERTY
  505.      This function finds the value of the property named PROPERTY in
  506.      SYMBOL's property list.  If there is no such property, `nil' is
  507.      returned.  Thus, there is no distinction between a value of
  508.      `nil' and the absence of the property.
  509.  
  510.      The name PROPERTY is compared with the existing property names
  511.      using `eq', so any object is a legitimate property.
  512.  
  513.      See `put' for an example.
  514.  
  515.  * Function: put SYMBOL PROPERTY VALUE
  516.      This function puts VALUE onto SYMBOL's property list under the
  517.      property name PROPERTY, replacing any previous value.
  518.  
  519.           (put 'fly 'verb 'transitive)
  520.                =>'transitive
  521.           (put 'fly 'noun '(a buzzing little bug))
  522.                => (a buzzing little bug)
  523.           (get 'fly 'verb)
  524.                => transitive
  525.           (symbol-plist 'fly)
  526.                => (verb transitive noun (a buzzing little bug))
  527.  
  528.  
  529. 
  530. File: elisp,  Node: Evaluation,  Next: Control Structures,  Prev: Symbols,  Up: Top
  531.  
  532. Evaluation
  533. **********
  534.  
  535.    The "evaluation" of expressions in Emacs Lisp is performed by the
  536. "Lisp interpreter"--a program that receives a Lisp object as input
  537. and computes its "value as an expression".  The value is computed in
  538. a fashion that depends on the data type of the object, following
  539. rules described in this chapter.  The interpreter runs automatically
  540. to evaluate portions of your program, but can also be called
  541. explicitly via the Lisp primitive function `eval'.
  542.  
  543. * Menu:
  544.  
  545. * Intro Eval::  Evaluation in the scheme of things.
  546. * Eval::        How to invoke the Lisp interpreter explicitly.
  547. * Forms::       How various sorts of objects are evaluated.
  548. * Quoting::     Avoiding evaluation (to put constants in the program).
  549.  
  550.  
  551. 
  552. File: elisp,  Node: Intro Eval,  Next: Eval,  Prev: Evaluation,  Up: Evaluation
  553.  
  554. Introduction to Evaluation
  555. ==========================
  556.  
  557.    The Lisp interpreter, or evaluator, is the program which computes
  558. the value of an expression which is given to it.  When a function 
  559. written in Lisp is called, the evaluator computes the value of the
  560. function by evaluating the expressions in the function body.  Thus,
  561. running any Lisp program really means running the Lisp interpreter.
  562.  
  563.    How the evaluator handles an object depends primarily on the data
  564. type of the object.
  565.  
  566.    A Lisp object which is intended for evaluation is called an
  567. "expression" or a "form".  The fact that expressions are data objects
  568. and not merely text is one of the fundamental differences between
  569. Lisp-like languages and typical programming languages.  Any object
  570. can be evaluated, but in practice only numbers, symbols, lists and
  571. strings are evaluated very often.
  572.  
  573.    It is very common to read a Lisp expression and then evaluate the
  574. expression, but reading and evaluation are separate activities, and
  575. either can be performed alone.  Reading per se does not evaluate
  576. anything; it converts the printed representation of a Lisp object to
  577. the object itself.  It is up to the caller of `read' whether this
  578. object is a form to be evaluated, or serves some entirely different
  579. purpose.  *Note Input Functions::.
  580.  
  581.    Do not confuse evaluation with command key interpretation.  The
  582. editor command loop translates keyboard input into a command (an
  583. interactively callable function) using the current keymaps, and then
  584. uses `call-interactively' to invoke the command.  The execution of
  585. the command itself involves evaluation if the command is written in
  586. Lisp, but that is not a part of command key interpretation itself. 
  587. *Note Command Loop::.
  588.  
  589.    Evaluation is a recursive process.  That is, evaluation of a form
  590. may cause `eval' to be called again in order to evaluate parts of the
  591. form.  For example, evaluation of a function call first evaluates
  592. each argument of the function call, and then evaluates each form in
  593. the function body.  Consider evaluation of the form `(car x)': the
  594. subform `x' must first be evaluated recursively, so that its value
  595. can be passed as an argument to the function `car'.
  596.  
  597.    The evaluation of forms takes place in a context called the
  598. "environment", which consists of the current values and bindings of
  599. all Lisp variables.  Whenever the form refers to a variable without
  600. creating a new binding for it, the value of the current binding is
  601. used.  *Note Variables::.
  602.  
  603.    Evaluation of a form may create new environments for recursive
  604. evaluation by binding variables (*note Local Variables::.).  These
  605. environments are temporary and will be gone by the time evaluation of
  606. the form is complete.  The form may also make changes that persist;
  607. these changes are called "side-effects".  An example of a form that
  608. produces side-effects is `(setq foo 1)'.
  609.  
  610.    Finally, evaluation of one particular function call, `byte-code',
  611. invokes the "byte-code interpreter" on its arguments.  Although the
  612. byte-code interpreter is not the same as the Lisp interpreter, it
  613. uses the same environment as the Lisp interpreter, and may on
  614. occasion invoke the Lisp interpreter.  (*Note Byte Compilation::.)
  615.  
  616.    The details of what evaluation means for each kind of form are
  617. described below (*note Forms::.).
  618.  
  619.  
  620. 
  621. File: elisp,  Node: Eval,  Next: Forms,  Prev: Intro Eval,  Up: Evaluation
  622.  
  623. Eval
  624. ====
  625.  
  626.    Most often, forms are evaluated automatically, by virtue of their
  627. occurrence in a program being run.  On rare occasions, you may need
  628. to write code that evaluates a form that is computed at run time,
  629. such as when the form is read from text being edited or found on a
  630. property list.  On these occasions, use the `eval' function.
  631.  
  632.    The functions and variables described in this section evaluate
  633. forms, specify limits to the evaluation process, or record recently
  634. returned values.  Evaluation is also performed by `load' (*note
  635. Loading::.).
  636.  
  637.  * Function: eval FORM
  638.      This is the basic function for performing evaluation.  It
  639.      evaluates FORM in the current environment and returns the
  640.      result.  How the evaluation proceeds depends on the type of the
  641.      object (*note Forms::.).
  642.  
  643.      Since `eval' is a function, the argument expression that appears
  644.      in a call to `eval' is evaluated twice: once as preparation
  645.      before `eval' is called, and again by the `eval' function itself.
  646.      Here is an example:
  647.  
  648.           (setq foo 'bar)
  649.                => bar
  650.           (setq bar 'baz)
  651.                => baz
  652.           ;; `eval' is called on the form `bar', which is the value of `foo'
  653.           (eval foo)
  654.                => baz
  655.  
  656.      The number of currently active calls to `eval' is limited to
  657.      `max-lisp-eval-depth'.
  658.  
  659.  * Command: eval-current-buffer &optional STREAM
  660.      This function evaluates the forms in the current buffer.  It
  661.      reads forms from the buffer and calls `eval' on them until the
  662.      end of the buffer is reached, or until an error is signaled and
  663.      not handled.
  664.  
  665.      If STREAM is supplied, the variable `standard-output' is bound
  666.      to STREAM during the evaluation (*note Output Functions::.).
  667.  
  668.      `eval-current-buffer' always returns `nil'.
  669.  
  670.  * Command: eval-region START END &optional STREAM
  671.      This function evaluates the forms in the current buffer in the
  672.      region defined by the positions START and END.  It reads forms
  673.      from the region and calls `eval' on them until the end of the
  674.      region is reached, or until an error is signaled and not handled.
  675.  
  676.      If STREAM is supplied, `standard-output' is bound to it for the
  677.      duration of the command.
  678.  
  679.      `eval-region' always returns `nil'.
  680.  
  681.  * Variable: max-lisp-eval-depth
  682.      This variable defines the maximum depth allowed in calls to
  683.      `eval', `apply', and `funcall' before an error is signaled (with
  684.      error message `"Lisp nesting exceeds max-lisp-eval-depth"'). 
  685.      `eval' is called recursively to evaluate the arguments of Lisp
  686.      function calls and to evaluate bodies of functions.
  687.  
  688.      This limit, with the associated error when it is exceeded, is
  689.      one way that Lisp avoids infinite recursion on an ill-defined
  690.      function.
  691.  
  692.      The default value of this variable is 200.  If you set it to a
  693.      value less than 100, Lisp will reset it to 100 if the given
  694.      value is reached.
  695.  
  696.  * Variable: values
  697.      The value of this variable is a list of values returned by all
  698.      expressions which were read from buffers (including the
  699.      minibuffer), evaluated, and printed.  The elements are in order,
  700.      most recent first.
  701.  
  702.           (setq x 1)
  703.                => 1
  704.           (list 'A (1+ 2) auto-save-default)
  705.                => (A 3 t)
  706.           values
  707.                => ((A 3 t) 1 ...)
  708.  
  709.      This variable is useful for referring back to values of forms
  710.      recently evaluated.  It is generally a bad idea to print the
  711.      value of `values' itself, since this may be very long.  Instead,
  712.      examine particular elements, like this:
  713.  
  714.           ;; Refer to the most recent evaluation result.
  715.           (nth 0 values)
  716.                => (A 3 t)
  717.           ;; That put a new element on, so all elements move back one.
  718.           (nth 1 values)
  719.                => (A 3 t)
  720.           ;; This gets the element that was next-to-last before this example.
  721.           (nth 3 values)
  722.                => 1
  723.  
  724.  
  725. 
  726. File: elisp,  Node: Forms,  Next: Quoting,  Prev: Eval,  Up: Evaluation
  727.  
  728. Kinds of Forms
  729. ==============
  730.  
  731.    A Lisp object that is intended to be evaluated is called a "form".
  732. How Emacs evaluates a form depends on its data type.  Emacs has three
  733. different kinds of form that are evaluated differently: symbols,
  734. lists, and "all other types".  All three kinds are described in this
  735. section, starting with "all other types" which are self-evaluating
  736. forms.
  737.  
  738. * Menu:
  739.  
  740. * Self-Evaluating Forms::   Forms that evaluate to themselves.
  741. * Symbol Forms::            Symbols evaluate as variables.
  742. * Classifying Lists::       How to distinguish various sorts of list forms.
  743. * Function Forms::          Forms that call functions.
  744. * Macro Forms::             Forms that call macros.
  745. * Special Forms::           "Special forms" are idiosyncratic primitives,
  746.                               most of them extremely important.
  747. * Autoloading::             Functions set up to load files
  748.                               containing their real definitions.
  749.  
  750.  
  751. 
  752. File: elisp,  Node: Self-Evaluating Forms,  Next: Symbol Forms,  Prev: Forms,  Up: Forms
  753.  
  754. Self-Evaluating Forms
  755. ---------------------
  756.  
  757.    A "self-evaluating form" is any form that is not a list or symbol.
  758. Self-evaluating forms evaluate to themselves: the result of
  759. evaluation is the same object that was evaluated.  Thus, the number
  760. 25 evaluates to 25, and the string `"foo"' evaluates to the string
  761. `"foo"'.  Likewise, evaluation of a vector does not cause evaluation
  762. of the elements of the vector--it returns the same vector with its
  763. contents unchanged.
  764.  
  765.      '123               ; An object, shown without evaluation.
  766.           => 123
  767.      123                ; Evaluated as usual---result is the same.
  768.           => 123
  769.      (eval '123)        ; Evaluated ``by hand''---result is the same.
  770.           => 123
  771.      (eval (eval '123)) ; Evaluating twice changes nothing.
  772.           => 123
  773.  
  774.    It is common to write numbers, characters, strings, and even
  775. vectors in Lisp code, taking advantage of the fact that they
  776. self-evaluate.  However, it is quite unusual to do this for types
  777. that lack a read syntax, because it is inconvenient and not very
  778. useful; however, it is possible to put them inside Lisp programs when
  779. they are constructed from subexpressions rather than read.  Here is
  780. an example:
  781.  
  782.      ;; Build such an expression.
  783.      (setq buffer (list 'print (current-buffer)))
  784.           => (print #<buffer eval.texi>)
  785.      ;; Evaluate it.
  786.      (eval buffer)
  787.           -| #<buffer eval.texi>
  788.           => #<buffer eval.texi>
  789.  
  790.  
  791. 
  792. File: elisp,  Node: Symbol Forms,  Next: Classifying Lists,  Prev: Self-Evaluating Forms,  Up: Forms
  793.  
  794. Symbol Forms
  795. ------------
  796.  
  797.    When a symbol is evaluated, it is treated as a variable.  The
  798. result is the variable's value, if it has one.  If it has none (if
  799. its value cell is void), an error is signaled.  For more information
  800. on the use of variables, see *Note Variables::.
  801.  
  802.    In the following example, the value of a symbol is set with
  803. `setq'.  When the symbol is later evaluated, that value is returned.
  804.  
  805.      (setq a 123)
  806.           => 123
  807.      (eval 'a)
  808.           => 123
  809.      a
  810.           => 123
  811.  
  812.    The symbols `nil' and `t' are treated specially, so that the value
  813. of `nil' is always `nil', and the value of `t' is always `t'.  Thus,
  814. these two symbols act like self-evaluating forms, even though `eval'
  815. treats them like any other symbol.
  816.  
  817.  
  818. 
  819. File: elisp,  Node: Classifying Lists,  Next: Function Forms,  Prev: Symbol Forms,  Up: Forms
  820.  
  821. Classification of List Forms
  822. ----------------------------
  823.  
  824.    A form that is a nonempty list is either a function call, a macro
  825. call, or a special form, according to its first element.  These three
  826. kinds of forms are evaluated in different ways, described below.  The
  827. rest of the list consists of "arguments" for the function, macro or
  828. special form.
  829.  
  830.    The first step in evaluating a nonempty list is to examine its
  831. first element.  This element alone determines what kind of form the
  832. list is and how the rest of the list is to be processed.  The first
  833. element is *not* evaluated, as it would be in some Lisp dialects
  834. including Scheme.
  835.  
  836.    If the first element of the list is a symbol, as it most commonly
  837. is, then the symbol's function cell is examined, and its contents are
  838. used instead of the original symbol.  If the contents are another
  839. symbol, this process, called "symbol function indirection", is
  840. repeated until a non-symbol is obtained.
  841.  
  842.    One possible consequence of this process is an infinite loop, in
  843. the event that a symbol's function cell refers to the same symbol. 
  844. Or a symbol may have a void function cell, causing a `void-function'
  845. error.  But if neither of these things happens, we eventually obtain
  846. a non-symbol, which ought to be a function or other suitable object.
  847.  
  848.    More precisely, we should now have a Lisp function (a lambda
  849. expression), a primitive function, a Lisp macro, a special form, or
  850. an autoload object.  Each of these types is a case described in one
  851. of the following sections.  If the object is not one of these types,
  852. the error `invalid-function' is signaled.
  853.  
  854.    The following example illustrates the symbol indirection process. 
  855. We use `fset' to set the function cell of a symbol and
  856. `symbol-function' to get the function cell contents (*note Function
  857. Cells::.).  Specifically, we store the symbol `car' into the function
  858. cell of `first', and the symbol `first' into the function cell of
  859. `erste'.
  860.  
  861.         ;; Build this function cell linkage:
  862.      ;;    -------------       -----        -------        -------
  863.      ;;   | #<subr car> | <-- | car |  <-- | first |  <-- | erste |
  864.      ;;    -------------       -----        -------        -------
  865.  
  866.  
  867.           (symbol-function 'car)
  868.           => #<subr car>
  869.      (fset 'first 'car)
  870.           => car
  871.      (fset 'erste 'first)
  872.           => first
  873.  
  874.         (erste '(1 2 3))           ; Call the function referenced by `erste'.
  875.           => 1
  876.  
  877.    By contrast, the following example calls a function without any
  878. symbol function indirection, because the first element is an
  879. anonymous Lisp function, not a symbol.
  880.  
  881.      ((lambda (arg) (erste arg))
  882.       '(1 2 3)) 
  883.           => 1
  884.  
  885. After that function is called, its body is evaluated; this does
  886. involve symbol function indirection when calling `erste'.
  887.  
  888.  
  889. 
  890. File: elisp,  Node: Function Forms,  Next: Macro Forms,  Prev: Classifying Lists,  Up: Forms
  891.  
  892. Evaluation of Function Forms
  893. ----------------------------
  894.  
  895.    If the first element of a list being evaluated is a Lisp function
  896. object or primitive function object, then that list is a "function
  897. call".  For example, here is a call to the function `+':
  898.  
  899.      (+ 1 x)
  900.  
  901.    When a function call is evaluated, the first step is to evaluate
  902. the remaining elements of the list in the order they appear.  The
  903. results are the actual argument values, one argument from each
  904. element.  Then the function is called with this list of arguments,
  905. effectively using the function `apply' (*note Calling Functions::.). 
  906. If the function is written in Lisp, the arguments are used to bind
  907. the argument variables of the function (*note Lambda Expressions::.);
  908. then the forms in the function body are evaluated in order, and the
  909. result of the last one is used as the value of the function call.
  910.  
  911.  
  912. 
  913. File: elisp,  Node: Macro Forms,  Next: Special Forms,  Prev: Function Forms,  Up: Forms
  914.  
  915. Lisp Macro Evaluation
  916. ---------------------
  917.  
  918.    If the first element of a list being evaluated is a macro object,
  919. then the list is a "macro call".  When a macro call is evaluated, the
  920. elements of the rest of the list are *not* initially evaluated. 
  921. Instead, these elements themselves are used as the arguments of the
  922. macro.  The macro definition computes a replacement form, called the
  923. "expansion" of the macro, which is evaluated in place of the original
  924. form.  The expansion may be any sort of form: a self-evaluating
  925. constant, a symbol or a list.  If the expansion is itself a macro
  926. call, this process of expansion repeats until some other sort of form
  927. results.
  928.  
  929.    Normally, the argument expressions are not evaluated as part of
  930. computing the macro expansion, but instead appear as part of the
  931. expansion, so they are evaluated when the expansion is evaluated.
  932.  
  933.    For example, given a macro defined as follows:
  934.  
  935.      (defmacro cadr (x)
  936.        (list 'car (list 'cdr x)))
  937.  
  938. an expression such as `(cadr (assq 'handler list))' is a macro call,
  939. and its expansion is:
  940.  
  941.      (car (cdr (assq 'handler list)))
  942.  
  943. Note that the argument `(assq 'handler list)' appears in the expansion.
  944.  
  945.    *Note Macros::, for a complete description of Emacs Lisp macros.
  946.  
  947.  
  948. 
  949. File: elisp,  Node: Special Forms,  Next: Autoloading,  Prev: Macro Forms,  Up: Forms
  950.  
  951. Special Forms
  952. -------------
  953.  
  954.    A "special form" is a primitive function specially marked so that
  955. its arguments are not all evaluated.  Special forms define control
  956. structures or perform variable bindings--things which functions
  957. cannot do.
  958.  
  959.    Each special form has its own rules for which arguments are
  960. evaluated and which are used without evaluation.  Whether a
  961. particular argument is evaluated may depend on the results of
  962. evaluating other arguments.
  963.  
  964.    Here is a list, in alphabetical order, of all of the special forms
  965. in Emacs Lisp with a reference to where each is described.
  966.  
  967. `and'
  968.      *note Combining Conditions::.
  969.  
  970. `catch'
  971.      *note Catch and Throw::.
  972.  
  973. `cond'
  974.      *note Conditionals::.
  975.  
  976. `condition-case'
  977.      *note Errors::.
  978.  
  979. `defconst'
  980.      *note Defining Variables::.
  981.  
  982. `defmacro'
  983.      *note Defining Macros::.
  984.  
  985. `defun'
  986.      *note Defining Functions::.
  987.  
  988. `defvar'
  989.      *note Defining Variables::.
  990.  
  991. `function'
  992.      *note Anonymous Functions::.
  993.  
  994. `if'
  995.      *note Conditionals::.
  996.  
  997. `interactive'
  998.      *note Interactive Call::.
  999.  
  1000. `let'
  1001.      *note Local Variables::.
  1002.  
  1003. `let*'
  1004.      *note Local Variables::.
  1005.  
  1006. `or'
  1007.      *note Combining Conditions::.
  1008.  
  1009. `prog1'
  1010.      *note Sequencing::.
  1011.  
  1012. `prog2'
  1013.      *note Sequencing::.
  1014.  
  1015. `progn'
  1016.      *note Sequencing::.
  1017.  
  1018. `quote'
  1019.      *note Quoting::.
  1020.  
  1021. `save-excursion'
  1022.      *note Excursions::.
  1023.  
  1024. `save-restriction'
  1025.      *note Narrowing::.
  1026.  
  1027. `save-window-excursion'
  1028.      *note Window Configurations::.
  1029.  
  1030. `setq'
  1031.      *note Setting Variables::.
  1032.  
  1033. `setq-default'
  1034.      *note Creating Buffer-Local::.
  1035.  
  1036. `unwind-protect'
  1037.      *note Nonlocal Exits::.
  1038.  
  1039. `while'
  1040.      *note Iteration::.
  1041.  
  1042. `with-output-to-temp-buffer'
  1043.      *note Temporary Displays::.
  1044.  
  1045.      Common Lisp note: here are some comparisons of special forms in
  1046.      GNU Emacs Lisp and Common Lisp.  `setq', `if', and `catch' are
  1047.      special forms in both Emacs Lisp and Common Lisp.  `defun' is a
  1048.      special form in Emacs Lisp, but a macro in Common Lisp. 
  1049.      `save-excursion' is a special form in Emacs Lisp, but doesn't
  1050.      exist in Common Lisp.  `throw' is a special form in Common Lisp
  1051.      (because it must be able to throw multiple values), but it is a
  1052.      function in Emacs Lisp (which doesn't have multiple values).
  1053.  
  1054.  
  1055. 
  1056. File: elisp,  Node: Autoloading,  Prev: Special Forms,  Up: Forms
  1057.  
  1058. Autoloading
  1059. -----------
  1060.  
  1061.    The "autoload" feature allows you to call a function or macro
  1062. whose function definition has not yet been loaded into Emacs.  When
  1063. an autoload object appears as a symbol's function definition and that
  1064. symbol is used as a function, Emacs will automatically install the
  1065. real definition (plus other associated code) and then call that
  1066. definition.  (*Note Autoload::.)
  1067.  
  1068.  
  1069. 
  1070. File: elisp,  Node: Quoting,  Prev: Forms,  Up: Evaluation
  1071.  
  1072. Quoting
  1073. =======
  1074.  
  1075.    The special form `quote' returns its single argument "unchanged".
  1076.  
  1077.  * Special Form: quote OBJECT
  1078.      This special form returns OBJECT, without evaluating it.  This
  1079.      allows symbols and lists, which would normally be evaluated, to
  1080.      be included literally in a program.  (It is not necessary to
  1081.      quote numbers, strings, and vectors since they are
  1082.      self-evaluating.)  Use `function' instead of `quote' when
  1083.      quoting lambda expressions (*note Anonymous Functions::.).
  1084.  
  1085.      Because `quote' is used so often in programs, a convenient read
  1086.      syntax is defined for it.  An apostrophe character (`'')
  1087.      followed by a Lisp object (in read syntax) expands to a list
  1088.      whose first element is `quote', and whose second element is the
  1089.      object.  Thus, the read syntax `'x' is an abbreviation for
  1090.      `(quote x)'.
  1091.  
  1092.      Here are some examples of expressions that use `quote':
  1093.  
  1094.           (quote (+ 1 2))
  1095.                => (+ 1 2)
  1096.           (quote foo)
  1097.                => foo
  1098.           'foo
  1099.                => foo
  1100.           ''foo
  1101.                => (quote foo)
  1102.           '(quote foo)
  1103.                => (quote foo)
  1104.           ['foo]
  1105.                => [(quote foo)]
  1106.  
  1107.  
  1108. 
  1109. File: elisp,  Node: Control Structures,  Next: Variables,  Prev: Evaluation,  Up: Top
  1110.  
  1111. Control Structures
  1112. ******************
  1113.  
  1114.    A Lisp program consists of expressions or "forms" (*note Forms::.).
  1115. We control the order of execution of the forms by enclosing them in
  1116. "control structures".  Control structures are special forms which
  1117. control when, whether, or how many times to execute the forms they
  1118. contain.
  1119.  
  1120.    The simplest control structure is sequential execution: first form
  1121. A, then form B, and so on.  This is what happens when you write
  1122. several forms in succession in the body of a function, or at top
  1123. level in a file of Lisp code--the forms are executed in the order
  1124. they are written.  We call this "textual order".  For example, if a
  1125. function body consists of two forms A and B, evaluation of the
  1126. function evaluates first A and then B, and the function's value is
  1127. the value of B.
  1128.  
  1129.    Naturally, Emacs Lisp has many kinds of control structures,
  1130. including other varieties of sequencing, function calls,
  1131. conditionals, iteration, and (controlled) jumps.  The built-in
  1132. control structures are special forms since their subforms are not
  1133. necessarily evaluated.  You can use macros to define your own control
  1134. structure constructs (*note Macros::.).
  1135.  
  1136. * Menu:
  1137.  
  1138. * Sequencing::             Evaluation in textual order.
  1139. * Conditionals::           `if', `cond'.
  1140. * Combining Conditions::   `and', `or', `not'.
  1141. * Iteration::              `while' loops.
  1142. * Nonlocal Exits::         Jumping out of a sequence.
  1143.  
  1144.  
  1145. 
  1146. File: elisp,  Node: Sequencing,  Next: Conditionals,  Prev: Control Structures,  Up: Control Structures
  1147.  
  1148. Sequencing
  1149. ==========
  1150.  
  1151.    Evaluating forms in the order they are written is the most common
  1152. control structure.  Sometimes this happens automatically, such as in
  1153. a function body.  Elsewhere you must use a control structure
  1154. construct to do this: `progn', the simplest control construct of Lisp.
  1155.  
  1156.    A `progn' special form looks like this:
  1157.  
  1158.      (progn A B C ...)
  1159.  
  1160. and it says to execute the forms A, B, C and so on, in that order. 
  1161. These forms are called the body of the `progn' form.  The value of
  1162. the last form in the body becomes the value of the entire `progn'.
  1163.  
  1164.    When Lisp was young, `progn' was the only way to execute two or
  1165. more forms in succession and use the value of the last of them.  But
  1166. programmers found they often needed to use a `progn' in the body of a
  1167. function, where (at that time) only one form was allowed.  So the
  1168. body of a function was made into an "implicit `progn'": several forms
  1169. are allowed just as in the body of an actual `progn'.  Many other
  1170. control structures likewise contain an implicit `progn'.  As a
  1171. result, `progn' is not used as often as it used to be.  It is needed
  1172. now most often inside of an `unwind-protect', `and', or `or'.
  1173.  
  1174.  * Special Form: progn FORMS...
  1175.      This special form evaluates all of the FORMS, in textual order,
  1176.      returning the result of the final form.
  1177.  
  1178.           (progn (print "The first form")
  1179.                  (print "The second form")
  1180.                  (print "The third form"))
  1181.                -| "The first form"
  1182.                -| "The second form"
  1183.                -| "The third form"
  1184.           => "The third form"
  1185.  
  1186.    Two other control constructs likewise evaluate a series of forms
  1187. but return a different value:
  1188.  
  1189.  * Special Form: prog1 FORM1 FORMS...
  1190.      This special form evaluates FORM1 and all of the FORMS, in
  1191.      textual order, returning the result of FORM1.
  1192.  
  1193.           (prog1 (print "The first form")
  1194.                  (print "The second form")
  1195.                  (print "The third form"))
  1196.                -| "The first form"
  1197.                -| "The second form"
  1198.                -| "The third form"
  1199.           => "The first form"
  1200.  
  1201.      Here is a way to remove the first element from a list in the
  1202.      variable `x', then return the value of that former element:
  1203.  
  1204.           (prog1 (car x) (setq x (cdr x)))
  1205.  
  1206.  * Special Form: prog2 FORM1 FORM2 FORMS...
  1207.      This special form evaluates FORM1, FORM2, and all of the
  1208.      following FORMS, in textual order, returning the result of FORM2.
  1209.  
  1210.           (prog2 (print "The first form")
  1211.                  (print "The second form")
  1212.                  (print "The third form"))
  1213.                -| "The first form"
  1214.                -| "The second form"
  1215.                -| "The third form"
  1216.           => "The second form"
  1217.  
  1218.  
  1219. 
  1220. File: elisp,  Node: Conditionals,  Next: Combining Conditions,  Prev: Sequencing,  Up: Control Structures
  1221.  
  1222. Conditionals
  1223. ============
  1224.  
  1225.    Conditional control structures choose among alternatives.  Emacs
  1226. Lisp has two conditional forms: `if', which is much the same as in
  1227. other languages, and `cond', which is a generalized case statement.
  1228.  
  1229.  * Special Form: if CONDITION THEN-FORM ELSE-FORMS...
  1230.      `if' chooses between the THEN-FORM and the ELSE-FORMS based on
  1231.      the value of CONDITION.  If the evaluated CONDITION is
  1232.      non-`nil', THEN-FORM is evaluated and the result returned. 
  1233.      Otherwise, the ELSE-FORMS are evaluated in textual order, and
  1234.      the value of the last one is returned.  (The ELSE part of `if'
  1235.      is an example of an implicit `progn'.  *Note Sequencing::.)
  1236.  
  1237.      If CONDITION has the value `nil', and no ELSE-FORMS are given,
  1238.      `if' returns `nil'.
  1239.  
  1240.      `if' is a special form because the branch which is not selected
  1241.      is never evaluated--it is ignored.  Thus, in the example below,
  1242.      `true' is not printed because `print' is never called.
  1243.  
  1244.           (if nil 
  1245.               (print 'true) 
  1246.             'very-false)
  1247.           => very-false
  1248.  
  1249.  * Special Form: cond CLAUSE...
  1250.      `cond' chooses among an arbitrary number of alternatives.  Each
  1251.      CLAUSE in the `cond' must be a list.  The CAR of this list is
  1252.      the CONDITION; the remaining elements, if any, the BODY-FORMS. 
  1253.      Thus, a clause looks like this:
  1254.  
  1255.           (CONDITION BODY-FORMS...)
  1256.  
  1257.      `cond' tries the clauses in textual order, by evaluating the
  1258.      CONDITION of each clause.  If the value of CONDITION is
  1259.      non-`nil', the BODY-FORMS are evaluated, and the value of the
  1260.      last of BODY-FORMS becomes the value of the `cond'.  The
  1261.      remaining clauses are ignored.
  1262.  
  1263.      If the value of CONDITION is `nil', the clause "fails", so the
  1264.      `cond' moves on to the following clause, trying its CONDITION.
  1265.  
  1266.      If every CONDITION evaluates to `nil', so that every clause
  1267.      fails, `cond' returns `nil'.
  1268.  
  1269.      A clause may also look like this:
  1270.  
  1271.           (CONDITION)
  1272.  
  1273.      Then, if CONDITION is non-`nil' when tested, the value of
  1274.      CONDITION becomes the value of the `cond' form.
  1275.  
  1276.      The following example has four clauses, which test for the cases
  1277.      where the value of `x' is a number, string, buffer and symbol,
  1278.      respectively:
  1279.  
  1280.           (cond ((numberp x) x)
  1281.                  ((stringp x) x)
  1282.                  ((bufferp x)
  1283.                   (setq temporary-hack x) ; multiple body-forms
  1284.                   (buffer-name x))        ; in one clause
  1285.                  ((symbolp x) (symbol-value x)))
  1286.  
  1287.      Often we want the last clause to be executed whenever none of
  1288.      the previous clauses was successful.  To do this, we use `t' as
  1289.      the CONDITION of the last clause, like this: `(t BODY-FORMS)'. 
  1290.      The form `t' evaluates to `t', which is never `nil', so this
  1291.      clause never fails, provided the `cond' gets to it at all.
  1292.  
  1293.      For example,
  1294.  
  1295.           (cond ((eq a 1) 'foo)
  1296.                 (t "default"))
  1297.           => "default"
  1298.  
  1299.      This expression is a `cond' which returns `foo' if the value of
  1300.      `a' is 1, and returns the string `"default"' otherwise.
  1301.  
  1302.    Both `cond' and `if' can usually be written in terms of the other.
  1303. Therefore, the choice between them is a matter of taste and style. 
  1304. For example:
  1305.  
  1306.      (if A B C)
  1307.      ==
  1308.      (cond (A B) (t C))
  1309.  
  1310.  
  1311.